/*
 *                  BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 * 
 * Created on Jun 4, 2007
 * 
 */

package org.biojava.services.das.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.biojava.dasobert.das.Capabilities;
import org.biojava.dasobert.das.DasTimeFormat;
import org.biojava.dasobert.das2.io.DasSourceIndexWriterImpl;
import org.biojava.dasobert.das2.io.DasSourceWriter;
import org.biojava.dasobert.das2.io.DasSourceWriterImpl;
import org.biojava.dasobert.das2.io.RegistryDasSourceWriterImpl;
import org.biojava.dasobert.dasregistry.DasCoordinateSystem;
import org.biojava.dasobert.dasregistry.DasSource;
import org.biojava.services.das.dao.OrganismBean;
import org.biojava.services.das.registry.DasRegistrySql;
import org.biojava.utils.xml.PrettyXMLWriter;
import org.biojava.utils.xml.XMLWriter;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ServletResponseWriter {

	//public static final String XML_CONTENT_TYPE = "application/x-das-sources+xml";
	public static final String XML_CONTENT_TYPE = "application/xml";
	public static final String XDASOK = "200";
    //X-DAS-Version - the protocol version (currently "DAS/1.6")
    //X-DAS-Status - a three digit status code which indicates the outcome of the request
    //X-DAS-Capabilities - describes the parts of of the specification the server implements
    //X-DAS-Server - the server name and version

	public ServletResponseWriter(){

	}



	private  XMLWriter initSourcesResponse(PrintWriter pw, int total, int start, int end) throws IOException{

		PrettyXMLWriter xw = new PrettyXMLWriter(pw);
		xw.printRaw("<?xml version='1.0' encoding='UTF-8' ?>");   
		//xw.printRaw("<?xml-stylesheet type=\"text/xsl\" href=\"das.xsl\"?>");    
		//System.out.println("XXXXX");
		xw.openTag("SOURCES");
		if(start!=0 ){
		xw.attribute("total",String.valueOf(total));
		xw.attribute("start",  String.valueOf(start));
		xw.attribute("end",  String.valueOf(end));
		}
		//xw.attribute("xml:base","http://das.sanger.ac.uk/registry/das2/");
		return xw;

	}    

//this method should only be in the registry response writer
//	public void writeLastModified(HttpServletResponse resp)	
//	throws ServletException{
//		resp.setHeader("Content-Encoding","ISO-8859-1");
//		resp.setHeader("Content-Type", XML_CONTENT_TYPE);
//
//		try {
//			OutputStream s = resp.getOutputStream();
//
//			PrintWriter pw = new PrintWriter(s);
//			PrettyXMLWriter xw = new PrettyXMLWriter(pw);
//			xw.printRaw("<?xml version='1.0' encoding='UTF-8' ?>");   			
//			//System.out.println("XXXXX");
//			xw.openTag("LASTMODIFIED");
//
//			BeanFactory ctx=(new ClassPathXmlApplicationContext("SpringDAO.xml"));
//		DasRegistrySql registry=(DasRegistrySql)ctx.getBean("registryBean");
//			Date d = registry.getlastModified();
//
//			xw.attribute("time", DasTimeFormat.toDASString(d) );
//			xw.closeTag("LASTMODIFIED");
//
//			xw.close();
//		} catch ( IOException e ){
//			e.printStackTrace();
//		}
//
//	}

	/** write the DAS-XML sources response for the provided DAS sources
	 * 
	 * @param resp
	 * @param sources
	 * @param start TODO
	 * @param end TODO
	 * @param times TODO
	 * @param end2 
	 * @throws ServletException
	 * @throws IOException
	 */
	public  void writeResponse(HttpServletResponse resp, List<DasSource> sources,  int total,int start, int end, boolean times)
	throws ServletException, IOException {
		resp.setHeader("Content-Encoding","ISO-8859-1");
		resp.setHeader("Content-Type", XML_CONTENT_TYPE);
		resp.setHeader("X-DAS-Status", XDASOK);

		OutputStream s = resp.getOutputStream();

		PrintWriter pw = new PrintWriter(s);
		if(end==0)end=sources.size();
		XMLWriter xw = initSourcesResponse(pw, total, start, end);
		DasSourceWriter writer = new DasSourceWriterImpl();       
		for ( int i = 0 ; i< sources.size();i++){
			DasSource source = sources.get(i);
			writer.writeDasSource(xw, source, times);
		}
		xw.closeTag("SOURCES");
		xw.close();
		
	}
	

	
	

	public void writeCoordinateSystemResponse(HttpServletResponse resp, 
			List<DasCoordinateSystem> dcs, int start, int stop, int totalCoordinatesForQuery){
		resp.setHeader("Content-Encoding","ISO-8859-1");
		resp.setHeader("Content-Type", XML_CONTENT_TYPE);
		resp.setHeader("X-DAS-Status", XDASOK);
		try {
			OutputStream s = resp.getOutputStream();

			PrintWriter pw = new PrintWriter(s);
			PrettyXMLWriter xw = new PrettyXMLWriter(pw);
			xw.printRaw("<?xml version='1.0' encoding='UTF-8' ?>");
			xw.openTag("DASCOORDINATESYSTEM");
			if(start!=0){
			xw.attribute("start", String.valueOf(start));
			xw.attribute("end", String.valueOf(stop));
			
			xw.attribute("total",String.valueOf(totalCoordinatesForQuery));
			}
			DasSourceWriter writer = new RegistryDasSourceWriterImpl();
			for (int i = 0; i < dcs.size(); i++) {
				DasCoordinateSystem coord = dcs.get(i);				
				writer.writeCoordinateSystem(xw, coord);
			}
			xw.closeTag("DASCOORDINATESYSTEM");

			xw.close();
		} catch (IOException e){
			e.printStackTrace();
		}

	}

	public void writeOrganismResponse(HttpServletResponse resp, OrganismBean[] organisms){
		resp.setHeader("Content-Encoding","ISO-8859-1");
		resp.setHeader("Content-Type", XML_CONTENT_TYPE);
		resp.setHeader("X-DAS-Status", XDASOK);
		try {
			OutputStream s = resp.getOutputStream();

			PrintWriter pw = new PrintWriter(s);
			PrettyXMLWriter xw = new PrettyXMLWriter(pw);
			xw.printRaw("<?xml version='1.0' encoding='UTF-8' ?>");

			//TODO: provide a .xsl stylesheet for this response
			//xw.printRaw("<?xml-stylesheet type=\"text/xsl\" href=\"das.xsl\"?>");    
			//System.out.println("XXXXX");
			xw.openTag("ORGANISMS");

			for (int i = 0; i < organisms.length; i++) {
				OrganismBean bean = organisms[i];
				if ( bean.getTaxonomyId() == 0 )
					continue;

				xw.openTag("ORGANISM");
				xw.attribute("uri","http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id="+ bean.getTaxonomyId());				
				xw.attribute("scientificName",bean.getScientificName());
				xw.attribute("name", bean.getName());
				xw.attribute("taxid", bean.getTaxonomyId()+"");

				xw.closeTag("ORGANISM");

			}
			xw.closeTag("ORGANISMS");

			xw.close();
		} catch (IOException e){
			e.printStackTrace();
		}
	}
	
	public void writeKnownCapabilities(HttpServletResponse resp, Capabilities []knownCapabilities){
		resp.setHeader("Content-Encoding","ISO-8859-1");
		resp.setHeader("Content-Type", XML_CONTENT_TYPE);
		resp.setHeader("X-DAS-Status", XDASOK);
		try {
			OutputStream s = resp.getOutputStream();

			PrintWriter pw = new PrintWriter(s);
			PrettyXMLWriter xw = new PrettyXMLWriter(pw);
			xw.printRaw("<?xml version='1.0' encoding='UTF-8' ?>");

			//TODO: provide a .xsl stylesheet for this response
			//xw.printRaw("<?xml-stylesheet type=\"text/xsl\" href=\"das.xsl\"?>");    
			//System.out.println("XXXXX");
			xw.openTag("CAPABILITIES");

			for (int i = 0; i < knownCapabilities.length; i++) {
				String  cap= knownCapabilities[i].toString();
			

				xw.openTag("CAPABILITY");
				
				xw.attribute("name", "das1:"+cap);
				xw.closeTag("CAPABILITY");

			}
			xw.closeTag("CAPABILITIES");

			xw.close();
		} catch (IOException e){
			e.printStackTrace();
		}
	}

}
